import { HttpClient } from '@angular/common/http';
import { Component, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';

import { MapService } from '../../core';

//侧边栏的底图切换和影像切换配置文件
@Component({
  selector: 'app-layer-tree-control',
  templateUrl: './layer-tree-control.component.html',
  styleUrls: ['./layer-tree-control.component.scss']
})
export class LayerTreeControlComponent implements OnInit, OnDestroy {
  @Output() lengendEmit = new EventEmitter<any>();
  type: ('basemaps' | 'images') = 'basemaps';
  showIndex = -1;
  currentMap = '';
  // layerListData = null;
  // 用户当前选择的底图的title
  selectLayer = '彩色版';
  basemaps = null;
  images = null;
  glmap = null;
  haslegend = false;
  configed = false;
  constructor(
    private mapService: MapService
  ) { }

  ngOnInit() {
    this.mapService.init().then(singleton => this.glmap = singleton);
    this.mapService.getStyleConfig().subscribe((conf: any) => {
      this.setConfig(conf);
    });
  }
  setConfig(conf) {
    this.basemaps = conf.basemaps;
    this.images = conf.images;
    this.basemaps[0].active = true;
    this.images[0].active = true;
    this.configed = true;
  }
  mapInit() {
    if (this[this.type]) {
      const item = this[this.type].find(item => item.active);
      if (item) {
        this.changeBaseMap(item);
      }
    } else {
      if (!this.configed) {
        this.mapService.getStyleConfig().subscribe((conf: any) => {
          this.setConfig(conf);
          const item = this[this.type].find(item => item.active);
          if (item) {
            this.changeBaseMap(item);
          }
        });
      }
    }
  }
  // 这块的逻辑快写哭了！
  switchClick(event) {
    // 两种情况（点击自己两次（相同则关闭！），点击自己一次再点击其他）
    if (this.showIndex === this.getShowIndexByType(event[0])) {
      // TODO: 新增，点击的是问题标记的时候会把当前状态进行同步到快捷指标卡上！
      if (event[0] === 'question') {
        postal.channel('QUESTION-MARK').publish('question-mark', false);
      }
      // ------------end--------------
      this.showIndex = -1;
      this.currentMap = (event[0] === 'layers' ? this.currentMap : event[0]); // basemap
      // 关闭按钮组依旧显示蓝色背景的状态
      postal.channel('BTN-CLOSE').publish('close-active');
      return;
    } else {
      this.showIndex = this.getShowIndexByType(event[0]);
      // 上面考虑的是关闭操作！，当操作是点击展开的操作呢？
      if (event[0] === 'layers' || this.currentMap === event[0] || event[0] === 'question') {
        // 假设你点击的是地图底图，地图加载成功，然后你又点了一下，这时候，地图底图选择面板关闭，然后你又点击了一下地图底图，这个时候，底图不会重新加载，而是什么操作也不做！这就是加这个判断的意义。同时，底图切换和图层树切不切换无关
        // TODO:新增：点击的是问题标记的时候会把当前状态进行同步到快捷指标卡上！
        if (event[0] === 'question') {
          postal.channel('QUESTION-MARK').publish('question-mark', true);
        }
        // ------------end--------------
        return;
      } else {
        this.currentMap = event[0];
        const activeInte = this[event[0]].find(i => { return i.active; });
        this.changeBaseMap(activeInte);
      }
    }
    // 判断用户选择的是不是basemaps或者images，如果是basemaps同时图层未彩色版，则颜色为黑色，否则为白色
    if (event[0] === 'basemaps' && this.selectLayer === '彩色版') {
      // 颜色为黑色
      postal.channel('CHANGE_COLOR').publish('set-color', false);
      sessionStorage.setItem('card_color', 'false');
    }
    else if (event[0] === 'images' || this.selectLayer === '深色版') {
      // 颜色为白色
      postal.channel('CHANGE_COLOR').publish('set-color', true);
      sessionStorage.setItem('card_color', 'true');
    }
  }
  // 这里也要写颜色变更
  getCurrentSel(e) {
    this.selectLayer = e.title;
    if (e.title !== '彩色版') {
      // 颜色为白色
      postal.channel('CHANGE_COLOR').publish('set-color', true);
      sessionStorage.setItem('card_color', 'true');
    } else {
      // 颜色为黑色
      postal.channel('CHANGE_COLOR').publish('set-color', false);
      sessionStorage.setItem('card_color', 'false');
    }
  }

  switchMouseEnter(event) {
    this.showIndex = this.getShowIndexByType(event[0]);
  }
  toggleList(state: 'show' | 'hide') {
    this.showIndex = -1;
  }
  resetSwitchLayer() {
    this.images.forEach(element => {
      element.active = false;
    });
    this.images[0].active = true;
    this.basemaps.forEach(element => {
      element.active = false;
    });
    this.basemaps[0].active = true;
  }
  // 显示类别更具索引
  getShowIndexByType(type) {
    switch (type) {
      case 'basemaps':
        return 0;
      case 'images':
        return 1;
      case 'layers':
        return 2;
      case 'question':
        return 3;
    }
  }
  changeBaseMap(baseItem) {
    const { style } = baseItem;
    this.removeBaseLayer();
    this.mapService.addNewBaseMap(style, { baseMap: true });
  }
  removeBaseLayer() {
    const baseStyleJson = this.glmap.getStyle();
    const removeLayers = [];
    for (let item of baseStyleJson.layers) {
      if (item.id === 'sp-layer-fill') {
        break;
      }
      removeLayers.push(item);
    }
    const removeSource = new Set();
    for (const layer of removeLayers) {

      if (this.glmap.getLayer(layer.id)) {
        this.glmap.removeLayer(layer.id);
        removeSource.add(layer.source);
      }
    }
    Array.from(removeSource).forEach(key => {
      if (this.glmap.getSource(key)) {
        this.glmap.removeSource(key);
      }
    });
  }
  // tianlk：路由模块的切换会导致图层树的改变，图层树应该勾选的图层是我一个一个的添加进去的。所以图例这边会一直被触发6遍。
  showLegend(legends) {
    if (legends.length > 0) {
      this.haslegend = true;
    }
    this.lengendEmit.emit(legends);
  }
  mapImgClick(event) {
    let [type, index] = event;
    this.changeBaseMap(this[type][index]);
  }
  ngOnDestroy() {
  }
}
